/*
 * @Author: 赵克强 huohuo625@163.com
 * @Date: 2023-10-17 10:13:29
 * @LastEditors: 赵克强 huohuo625@163.com
 * @LastEditTime: 2025-01-20 16:10:12
 * @FilePath: \hy-ui\src\permission.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isRelogin } from '@/utils/request'

NProgress.configure({ showSpinner: false })

const whiteList = ['/sso', '/login', '/register', '/noAuth', '/fileView']

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
    // if (to.path === '/login') {
    //   next({ path: '/index' })
    //   NProgress.done()
    // } else {
    if (store.getters.roles.length === 0) {
      isRelogin.show = true
      // 判断当前用户是否已拉取完user_info信息
      //{type:'GetInfo',key:'sys_user'}
      store.dispatch({ type: 'GetInfo' }).then((res) => {
        isRelogin.show = false
        if (res?.data?.user?.userType === "sys_user") {
          store.dispatch({ type: 'GenerateRoutes' }).then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            router.addRoutes(accessRoutes) // 动态添加可访问路由表
            if (to.query?.isFirstLogin || to.fullPath === '/') {
              next({ path: "/app/appInfo", replace: true })
            } else {
              next({ ...to, replace: true })
            }
            // hack方法 确保addRoutes已完成
          })
        } else {
          store.dispatch({ type: 'GetInfo', key: 'front_user' }).then(response => {
            store.dispatch({ type: 'GenerateRoutes', key: 'front_user' }).then(accessRoutes => {
              // 根据roles权限生成可访问的路由表
              router.addRoutes(accessRoutes) // 动态添加可访问路由表
              if (to.query?.isFirstLogin || to.fullPath === '/') {
                next({ path: "/index", replace: true })
              } else {
                next({ ...to, replace: true })
              }
            })
          }).catch(err => {
            store.dispatch('LogOut').then(() => {
              Message.error(err)
              next({ path: '/index' })
            })
          })
        }
      }).catch(err => {
        store.dispatch('LogOut').then(() => {
          Message.error(err)
          next({ path: '/index' })
        })
      })
    } else {
      next()
    }
    // }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
